<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\WechatUserModel;

class DistributionShopJobTitleAliasController extends BackgroundController {
	
	protected function _initialize() {
		$this->setControllerTitle('头衔别名管理');
		$this->setActionTitle(array(
				'index' => '头衔列表',
		));
		$this->setActionNav(array(
				'index',
		));
	}
	
	public function indexAction() {
	    /* 获得等级配置 */
	    $distributionShop = M("DistributionShop")->where(array('cid'=>$this->aid))->find();
	    $distributionShop['level_config'] and $distributionShop['level_config'] = unserialize($distributionShop['level_config']);
	    $levelIO = $distributionShop['level_config']; // 等级开关
	    /* 头衔列表 */
		$jobTitleList = M("DistributionShopJobTitle a")->join("__DISTRIBUTION_SHOP_JOB_TITLE_ALIAS__ b on a.id = b.type and b.cid = {$this->aid}", "LEFT")
									->field("a.id,a.hasLevel,a.name,b.aliasName,b.levelAlias") // (case b.aliasName when b.aliasName then b.aliasName else a.name end) as name,
									->select();
		foreach ( $jobTitleList as $k => &$v ) {
		    $v['hasLevel'] = ($v['hasLevel'] or $levelIO[$v['id']]) ? 1 : 0;
		    if ( $v["hasLevel"] ) {
		        if ( $v['levelAlias'] ) {
		            $v['levelAlias'] = unserialize( $v['levelAlias'] );
		        } else {
		            for ( $i=0; $i<10; $i++) {
		                $v['levelAlias'][$i] = "";
		            }
		        }
		    }
		}
		$this->assign("jobTitleList", $jobTitleList);
		$this->display();
	}
	
	public function saveAction() {
		$jobTitle = I("jobTitle");
		$alias = M("DistributionShopJobTitleAlias")->where(array('cid' => $this->aid))->getField("type,aliasName");
		foreach($jobTitle as $typeId => $aliasName ) {
			if ( isset($alias[$typeId]) ) {
			    $levelAlias = $jobTitle[$typeId]['levelAlias'];
				M("DistributionShopJobTitleAlias")->where(array('cid' => $this->aid, 'type' => $typeId,))->save(array(
					'aliasName' => $jobTitle[$typeId]['aliasName'] ? $jobTitle[$typeId]['aliasName'] : "",
					'levelAlias' => $levelAlias?serialize($levelAlias):null,
				));
			} else {
			    $levelAlias = $jobTitle[$typeId]['levelAlias'];
				M("DistributionShopJobTitleAlias")->add(array(
					'type' => $typeId,
					'cid' => $this->aid,
					'aliasName' => $jobTitle[$typeId]['aliasName'],
					'levelAlias' => $levelAlias?serialize($levelAlias):null,
				));
			}
		}
		$this->ajaxSuccess("保存成功");
	}
	
}
